package com.leyou.user.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptiion.LyException;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.config.UserPropertites;
import com.leyou.user.util.CodecUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserServiceImpl
 * @Date 2019/2/23 19:49
 */
@Service
@EnableConfigurationProperties(UserPropertites.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private UserPropertites prop;

    private static final String KEY_PREFIX = "user:verify:phone";

    @Override
    public void sendCode(Long phone) {
        //生成key
        String key = KEY_PREFIX + phone;
        Map<String, Object> msg = new HashMap<>();
        //生成验证码
        String code = NumberUtils.generateCode(6);
        msg.put("phone", phone);
        msg.put("code", code);
        //发送验证码
        amqpTemplate.convertAndSend(prop.getExchange(), prop.getRoutingKey(), msg);

        //保存验证码到redis
        redisTemplate.opsForValue().set(key, code, prop.getTimeOut(), TimeUnit.MINUTES);
    }

    @Override
    @Transactional
    public void registerUser(User user, String code) {
        //获取redis中的验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(code, cacheCode)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_CODE);
        }
        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //密码加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));

        user.setCreated(new Date());
        //注册用户
        userMapper.insert(user);
    }

    @Override
    public User queryUserByNameAndPwd(String username, String password) {
        //查询用户名
        User user = new User();
        user.setUsername(username);
        //校验用户名
        User u = userMapper.selectOne(user);
        if (u == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_AND_PASSWORD);
        }
        //校验密码
        if (!StringUtils.equals(u.getPassword(), CodecUtils.md5Hex(password, u.getSalt()))) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_AND_PASSWORD);
        }
        
        //用户名密码正确
        return u;
    }

    @Override
    public Boolean checkUser(String data, Integer type) {
        User u = new User();
        switch (type) {
            case 1:
                u.setUsername(data);
                break;
            case 2:
                u.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_USER_DATA_TYPE);
        }
        return userMapper.selectCount(u) == 0;
    }
}
